from cloudinary.models import CloudinaryField
from django.db import models
from django.conf import settings
from django.db.models import Avg
from django.utils import timezone


class ActivityCategory(models.Model):
    """活动分类"""
    name = models.CharField(max_length=50, unique=True, verbose_name='分类名称')
    description = models.TextField(blank=True, verbose_name='分类描述')
    icon = models.CharField(max_length=50, blank=True, verbose_name='图标类名')
    is_default = models.BooleanField(default=False, verbose_name='是否默认分类')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'activity_categories'
        verbose_name = '活动分类'
        verbose_name_plural = '活动分类'
    
    def __str__(self):
        return self.name


class Activity(models.Model):
    """活动"""
    STATUS_CHOICES = (
        ('pending', '待审核'),
        ('approved', '已通过'),
        ('rejected', '已拒绝'),
        ('cancelled', '已取消'),
        ('completed', '已完成'),
    )
    
    title = models.CharField(max_length=200, verbose_name='活动标题')
    description = models.TextField(verbose_name='活动描述')
    category = models.ForeignKey(ActivityCategory, on_delete=models.SET_NULL, null=True, verbose_name='活动分类')
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='created_activities', verbose_name='创建者')
    
    # 时间地点
    start_time = models.DateTimeField(verbose_name='开始时间')
    end_time = models.DateTimeField(verbose_name='结束时间')
    location = models.CharField(max_length=200, verbose_name='活动地点')
    latitude = models.DecimalField(max_digits=10, decimal_places=7, null=True, blank=True, verbose_name='纬度')
    longitude = models.DecimalField(max_digits=10, decimal_places=7, null=True, blank=True, verbose_name='经度')
    
    # 人数限制
    max_participants = models.IntegerField(verbose_name='最大参与人数')
    current_participants = models.IntegerField(default=0, verbose_name='当前参与人数')
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    
    # 图片
    # cover_image = models.ImageField(upload_to='activities/', null=True, blank=True, verbose_name='活动封面图片')
    # 活动封面图片 - 使用Cloudinary存储
    cover_image = CloudinaryField(
        '活动封面图片',  # verbose_name
        folder='meet/activities/covers/',  # 专门的活动封面文件夹
        # transformation=[
        #     {
        #         'width': 800,
        #         'height': 600,
        #         'crop': 'limit',
        #         'quality': 'auto:best'
        #     }
        # ],
        # format='jpg',
        blank=True,
        null=True,
    )

    # 统计
    view_count = models.IntegerField(default=0, verbose_name='浏览次数')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'activities'
        verbose_name = '活动'
        verbose_name_plural = '活动'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title
    
    def is_full(self):
        """判断活动是否已满"""
        return self.current_participants >= self.max_participants
    
    def get_average_rating(self):
        """获取平均评分"""
        avg = self.ratings.aggregate(Avg('score'))['score__avg']
        return round(avg, 1) if avg else 0
    
    def can_register(self):
        """判断是否可以报名"""
        return self.status == 'approved' and not self.is_full()


    def get_cover_image_url(self):
        """获取封面图片URL"""
        if self.cover_image:
            try:
                # 尝试使用 Cloudinary 的优化URL
                url = self.cover_image.build_url(
                    # width=800,
                    # height=600,
                    # crop="limit",
                    # quality="auto",
                    # format="auto"
                )
                return url
            except Exception as e:
                print(f"Cloudinary URL构建失败: {e}")
                # 如果构建失败，回退到原始URL
                try:
                    return self.cover_image.url
                except Exception:
                    # 如果连原始URL都获取失败，返回默认图片
                    return self.get_default_cover_url()
        return self.get_default_cover_url()

    def get_default_cover_url(self):
        """获取默认封面URL"""
        return '/static/imgs/default-activity-cover.jpeg'

    def can_user_rate(self, user):
        """检查用户是否可以评分此活动"""
        if not user.is_authenticated:
            return False

        # 用户必须已报名
        is_registered = self.registrations.filter(
            user=user,
            status='registered'
        ).exists()

        return is_registered

    def get_user_rating(self, user):
        """获取用户的评分"""
        if not user.is_authenticated:
            return None
        try:
            return self.ratings.get(user=user)
        except ActivityRating.DoesNotExist:
            return None

    def has_started(self):
        """检查活动是否已经开始"""
        return timezone.now() >= self.start_time

    def can_cancel_registration(self):
        """检查是否可以取消报名（活动开始前）"""
        return timezone.now() < self.start_time

    def can_check_in(self):
        """检查是否可以签到（活动开始后）"""
        return timezone.now() >= self.start_time

class ActivityRegistration(models.Model):
    """活动报名"""
    STATUS_CHOICES = (
        ('registered', '已报名'),
        ('cancelled', '已取消'),
        ('attended', '已参加'),
    )
    
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='registrations', verbose_name='活动')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='registrations', verbose_name='用户')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='registered', verbose_name='状态')
    is_checked_in = models.BooleanField(default=False, verbose_name='是否签到')
    checked_in_at = models.DateTimeField(null=True, blank=True, verbose_name='签到时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='报名时间')
    
    class Meta:
        db_table = 'activity_registrations'
        verbose_name = '活动报名'
        verbose_name_plural = '活动报名'
        unique_together = ['activity', 'user']
    
    def __str__(self):
        return f"{self.user.username} - {self.activity.title}"


class ActivityComment(models.Model):
    """活动评论"""
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='comments', verbose_name='活动')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='activity_comments', verbose_name='用户')
    content = models.TextField(verbose_name='评论内容')
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies', verbose_name='父评论')
    likes_count = models.IntegerField(default=0, verbose_name='点赞数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'activity_comments'
        verbose_name = '活动评论'
        verbose_name_plural = '活动评论'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.user.username} - {self.activity.title}"


class CommentImage(models.Model):
    """评论图片"""
    comment = models.ForeignKey(ActivityComment, on_delete=models.CASCADE, related_name='images', verbose_name='评论')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='上传用户')

    # 评论图片 - 使用Cloudinary存储
    image = CloudinaryField(
        '评论图片',
        folder='meet/comments/images/',
        transformation=[
            {
                'width': 800,
                'height': 600,
                'crop': 'limit',
                'quality': 'auto:best'
            }
        ],
        format='jpg',
    )

    description = models.CharField(max_length=200, blank=True, verbose_name='图片描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')

    class Meta:
        db_table = 'comment_images'
        verbose_name = '评论图片'
        verbose_name_plural = '评论图片'

    def __str__(self):
        return f"{self.comment.id} - {self.user.username}"

    def get_image_url(self):
        """获取图片URL"""
        try:
            if self.image:
                return self.image.url
        except Exception as e:
            print(f"获取图片URL错误: {e}")
        return "/static/imgs/default-image.jpg"

    def get_thumbnail_url(self):
        """获取图片缩略图URL"""
        try:
            if self.image:
                # 如果是 Cloudinary 字段，尝试构建缩略图URL
                if hasattr(self.image, 'build_url'):
                    return self.image.build_url(
                        width=200,
                        height=150,
                        crop="fill",
                        quality="auto",
                        format="auto"
                    )
                return self.image.url
        except Exception as e:
            print(f"获取缩略图URL错误: {e}")
        return "/static/imgs/default-image.jpg"




class ActivityRating(models.Model):
    """活动评分"""
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='ratings', verbose_name='活动')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='activity_ratings', verbose_name='用户')
    score = models.IntegerField(choices=[(i, f'{i}星') for i in range(1, 6)], verbose_name='评分')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'activity_ratings'
        verbose_name = '活动评分'
        verbose_name_plural = '活动评分'
        unique_together = ['activity', 'user']
    
    def __str__(self):
        return f"{self.user.username} - {self.activity.title} - {self.score}星"


class ActivityImage(models.Model):
    """活动图片"""
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='images', verbose_name='活动')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='上传用户')
    # image = models.ImageField(upload_to='activity_images/', verbose_name='图片')
    # 活动图片 - 使用Cloudinary存储
    image = CloudinaryField(
        '活动图片',  # verbose_name
        folder='meet/activities/images/',  # 专门的活动图片文件夹
        transformation=[
            {
                'width': 1200,
                'height': 900,
                'crop': 'limit',
                'quality': 'auto:best'
            }
        ],
        format='jpg',
    )
    description = models.CharField(max_length=200, blank=True, verbose_name='图片描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    
    class Meta:
        db_table = 'activity_images'
        verbose_name = '活动图片'
        verbose_name_plural = '活动图片'
    
    def __str__(self):
        return f"{self.activity.title} - {self.user.username}"

    def get_image_url(self):
        """获取图片URL"""
        return self.image.build_url(
            width=1200,
            height=900,
            crop="limit",
            quality="auto",
            format="auto"
        )

    def get_thumbnail_url(self):
        """获取图片缩略图URL"""
        return self.image.build_url(
            width=400,
            height=300,
            crop="fill",
            quality="auto",
            format="auto"
        )
